package com.sharedlease.websocket;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.sharedlease.entity.Chat;
import com.sharedlease.entity.Message;
import com.sharedlease.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;




@ServerEndpoint("/Websocket/{userId}")
@Component
public class UserWebsocketServer {


    public JdbcTemplate jdbcTemplate;

    public static int onlineCount = 0;

    public Session session;

    public static ConcurrentHashMap<String, UserWebsocketServer> websocketList = new ConcurrentHashMap<>();

    public static ConcurrentHashMap<String, List<String>> redisMessage = new ConcurrentHashMap<>();

    public  String userId;


    public String username = "";

    public UserWebsocketServer() {
        DriverManagerDataSource dataSource=new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://1.15.133.55:3306/sharedlease?serverTimezone=GMT%2B8");
        dataSource.setUsername("root");
        dataSource.setPassword("082908");
        jdbcTemplate=new JdbcTemplate(dataSource);
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.userId=userId;
        System.out.println("userId : " + userId);
        this.session = session;
        websocketList.put(userId,this);
        addOnlineCount();           //在线数加1
        String sql="select name from user where id="+userId+" union SELECT NAME  FROM merchant WHERE id="+userId;
        try {
            this.username = jdbcTemplate.queryForObject(sql, String.class);
        }catch (Exception e){

        }
    }

    @OnClose
    public void onClose() {
        if(websocketList.get(this.userId)!=null){
            websocketList.remove(this.userId);
            subOnlineCount();           //在线数减1
        }

    }


    @OnMessage
    public void onMessage(String message) {
        String notice = message.substring(0, message.lastIndexOf("`"));
        String dest_id = message.substring(message.lastIndexOf("`")+1);
        long id = IdWorker.getId();
        String sql="insert into chat(id,source_id,source_name,dest_id,message) values("+id+","+userId+",'"+username+"',"+dest_id+",'"+notice+"')";
        System.out.println(sql);
        jdbcTemplate.update(sql);
        Chat chat = new Chat();
        chat.setId(id);
        chat.setSourceId(Long.parseLong(userId));
        chat.setSourceName(username);
        chat.setDestId(Long.parseLong(dest_id));
        chat.setMessage(notice);
        chat.setHasRead(0);
        System.out.println("要发送的chat："+chat);
        String json = JSON.toJSONString(chat);
        if (websocketList.get(dest_id)!=null)
        {
            websocketList.get(dest_id).session.getAsyncRemote().sendText(json);

        }

    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }



    public List<String> getRedis(String id){
        if (id == null) {
            throw new NullPointerException();
        }
        List<String> list = redisMessage.get(id);
        redisMessage.remove(id);
        return list;
    }

    public void sendMessage(String id, Chat chat) throws IOException {
        if (id == null){
            throw new NullPointerException();
        }
        String json = JSON.toJSONString(chat);
        if (websocketList.containsKey(id)){
            websocketList.get(id).session.getAsyncRemote().sendText(json);
        }
        String sql="insert into chat(id,source_id,source_name,dest_id,message) values("+chat.getId()+","+chat.getSourceId()+",'"+chat.getSourceName()+"',"+chat.getDestId()+",'"+chat.getMessage()+"')";
        System.out.println(sql);
        jdbcTemplate.update(sql);

    }



    public void sendMessageToAll(Message message) throws IOException {
        for (String id : websocketList.keySet()){
            String json = JSON.toJSONString(message);
            websocketList.get(id).session.getAsyncRemote().sendText(json);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        UserWebsocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        UserWebsocketServer.onlineCount--;
    }

}
